from selenium import webdriver
from selenium.common.exceptions import TimeoutException, NoSuchElementException
from selenium.webdriver import ActionChains
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.remote.webdriver import WebDriver
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait


class BasePage:
    def __init__(self, driver: WebDriver = None):
        if driver is not None:
            self.driver = driver
        else:
            #浏览器复用，cmd“chrome --remote-debugging-port=9222”
            options = Options()
            options.debugger_address = '127.0.0.1:9222'
            self.driver = webdriver.Chrome(options=options)

    def find(self, by, element):
        WebDriverWait(self.driver, 15).until(expected_conditions.visibility_of_element_located((by, element)))
        return self.driver.find_element(by, element)


    def finds(self, by, element):
        WebDriverWait(self.driver, 15).until(expected_conditions.visibility_of_element_located((by, element)))
        return self.driver.find_elements(by, element)


    def click(self, by, element,timeout=10, check_loc: tuple = None):
        #self.find(by, element).click()
        def loop_click(driver):
            goal.click()
            return len(driver.find_elements(*check_loc)) > 0

        goal = self.find(by, element)
        if check_loc:
            WebDriverWait(self.driver, 5).until(loop_click)
        else:
            goal.click()

    def sendkeys(self, by, element, value):
        self.find(by, element).send_keys(value)







